﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Net;
using System.IO;

namespace Chap01_Web
{
    public partial class ShowAnonymousTypeDataBinding : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Update();
        }

        private void Update()
        {
            var quote1 = new { Stock = "DELL", Quote = GetQuote("DELL") };
            var quote2 = new { Stock = "MSFT", Quote = GetQuote("MSFT") };
            var quote3 = new { Stock = "GOOG", Quote = GetQuote("GOOG") };

            var quotes = new object[] { quote1, quote2, quote3 };
            DataList1.DataSource = quotes;
            DataList1.DataBind();
            Label3.Text = DateTime.Now.ToLongTimeString();
        }

        private string GetQuote(string stoke)
        {
            try
            {
                return InnerGetQuote(stoke);
            }
            catch (Exception ex)
            {
                Debug.Print(ex.Message);
                return "N/A";
            }
        }

        private string InnerGetQuote(string stoke)
        {
            string url = "http://quote.yahoo.com/d/quote.csv?s={0}&f=pc";
            var request = HttpWebRequest.Create(string.Format(url, stoke));

            using (var response = request.GetResponse())
            {
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    return reader.ReadToEnd();
                }
            }
        }

        protected void Timer1_Tick(object sender, EventArgs e)
        {
            Update();
        }
    }
}